package com.markerhub.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Web配置类，用于全局配置Spring MVC相关设置
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 注册全局日期格式化器
        DateFormatter dateFormatter = new DateFormatter("yyyy-MM-dd HH:mm:ss");
        registry.addFormatter(dateFormatter);
    }

    /**
     * 全局数据绑定器，处理空字符串到Date的转换
     */
    @ControllerAdvice
    public static class GlobalBindingInitializer {

        @InitBinder
        public void initBinder(WebDataBinder binder) {
            // 自定义Date编辑器，处理空字符串
            binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
                @Override
                public void setAsText(String text) {
                    if (text == null || text.trim().isEmpty()) {
                        setValue(null);
                    } else {
                        try {
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            setValue(dateFormat.parse(text));
                        } catch (ParseException e) {
                            // 尝试其他日期格式
                            try {
                                SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
                                setValue(dateFormat2.parse(text));
                            } catch (ParseException ex) {
                                setValue(null);
                            }
                        }
                    }
                }
            });
        }
    }
}